import tensorflow as tf
import os
import sys
from python_ai.common.xcommon import *
import numpy as np

model_path = '../../../../../../large_data/model/inceptionV3/tensorflow_inception_graph.pb'
input_img_path = '../../../../../../large_data/CV3/_many_files/agriculture/train/corn/corn_000.jpg'
VER = 'v2.0'
FILE_NAME = os.path.basename(__file__)
OUTPUT_DIR = os.path.join('_save', FILE_NAME, VER)
os.makedirs(OUTPUT_DIR, exist_ok=True)
OUTPUT_NAME = os.path.basename(input_img_path) + '.' + rand_name_on_now() + '.txt'
OUTPUT_PATH = os.path.join(OUTPUT_DIR, OUTPUT_NAME)

with open(model_path, 'rb') as f:
    bin = f.read()

graphDef = tf.GraphDef()
graphDef.ParseFromString(bin)

# DecodeJpeg: TypeError: Cannot interpret feed_dict key as Tensor: Can not convert a Operation into a Tensor.
# DecodeJpeg/contents: TypeError: Cannot interpret feed_dict key as Tensor: Can not convert a Operation into a Tensor.
# DecodeJpeg/contents:0 OK
# pool_3/_reshape Get None
# pool_3/_reshape:0 OK
input_placeholder, output_tensor = tf.import_graph_def(graphDef,
                                                       return_elements=[
                                                           'DecodeJpeg/contents:0',
                                                           'pool_3/_reshape:0'
                                                       ])

with open(input_img_path, 'rb') as f:
    img_bin = f.read()

with tf.Session() as sess:
    vec = sess.run(output_tensor, feed_dict={input_placeholder: img_bin})
    print(vec)
    print(f'Writing to {OUTPUT_PATH}')
    np.savetxt(OUTPUT_PATH, vec)
    print(f'Writtent to file.')
